package top.zlcode.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import top.zlcode.api.ai.RemoteChatService;
import top.zlcode.api.ai.domain.Message;
import top.zlcode.api.ai.domain.dto.ChatDTO;
import top.zlcode.api.ai.domain.vo.ChatVO;
import top.zlcode.common.core.context.UserContextHelper;
import top.zlcode.common.core.domain.R;
import top.zlcode.common.core.domain.TableDataInfo;
import top.zlcode.common.core.enums.ProgramType;
import top.zlcode.common.core.enums.QuestionResultType;
import top.zlcode.common.core.enums.ResultCode;
import top.zlcode.common.security.exception.ServiceException;
import top.zlcode.friend.domain.question.Question;
import top.zlcode.friend.domain.question.dto.QuestionCodeSuggestDTO;
import top.zlcode.friend.domain.question.es.QuestionES;
import top.zlcode.friend.domain.question.dto.QuestionQueryDTO;
import top.zlcode.friend.domain.question.vo.QuestionAnalysisVO;
import top.zlcode.friend.domain.question.vo.QuestionCodeSuggestVO;
import top.zlcode.friend.domain.question.vo.QuestionDetailVO;
import top.zlcode.friend.domain.question.vo.QuestionVO;
import top.zlcode.friend.domain.user.UserSubmit;
import top.zlcode.friend.elasticsearch.QuestionRepository;
import top.zlcode.friend.manager.QuestionCacheManager;
import top.zlcode.friend.mapper.question.QuestionMapper;
import top.zlcode.friend.mapper.user.UserSubmitMapper;
import top.zlcode.friend.service.question.IQuestionService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Autowired
    private RemoteChatService remoteChatService;

    @Value("${zlcode.ai.key}")
    private String aiKey;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        long count = questionRepository.count();
        if (count <= 0) {
            refreshQuestion();
        }

        // 构造 es 查询条件
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(), sort);
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();

        // 根据查询条件查询 es 数据
        Page<QuestionES> questionESPage;
        if (difficulty == null && StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findAll(pageable);
        } else if (StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty, pageable);
        } else if (difficulty == null) {
            questionESPage = questionRepository.findByTitleOrContent(StrUtil.trim(keyword), StrUtil.trim(keyword), pageable);
        } else {
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        }

        // 构造返回数据
        long total = questionESPage.getTotalElements();
        if (total == 0) {
            return TableDataInfo.empty();
        }

        List<QuestionES> questionESList = questionESPage.getContent();
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOList, total);
    }

    private void refreshQuestion() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<>());
        if (CollUtil.isEmpty(questionList)) {
            return;
        }
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        Question question = getById(questionId);
        BeanUtil.copyProperties(question, questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.nextQuestion(questionId).toString();
    }

    @Override
    public QuestionAnalysisVO analysis(Long questionId, Integer programType) {

        // 查询 redis 中是否是否有这个题目的解析
        QuestionAnalysisVO questionAnalysisVO = questionCacheManager.getAnalysis(questionId);
        if (questionAnalysisVO != null) {
            return questionAnalysisVO;
        }

        // 使用 ai 进行题目解析
        Question question = getById(questionId);
        return remoteCallAiAnalysis(question, programType);
    }

    @Override
    public QuestionCodeSuggestVO codeSuggest(QuestionCodeSuggestDTO dto) {

        Long uid = UserContextHelper.getUserId();

        // 查缓存, 看当前提交记录是否有过 ai 代码优化建议
        QuestionCodeSuggestVO cache = questionCacheManager.getCodeSuggest(uid, dto.getQuestionId(), dto.getUuid());
        if (cache != null) {
            return cache;
        }

        // 查到当前用户的这次提交记录
        UserSubmit userSubmit = userSubmitMapper.selectCurrentUserSubmit(uid, null, dto.getQuestionId(), dto.getUuid());
        if (userSubmit == null) {
            throw new ServiceException(ResultCode.QUESTION_SUBMIT_NOT_EXISTS);
        }

        // 未通过的记录, 无法让 ai 进行代码优化
        if (!userSubmit.getPass().equals(QuestionResultType.PASS.getValue())) {
            throw new ServiceException(ResultCode.QUESTION_CODE_SUGGEST_NOT_PASS);
        }

        // 查找出题目信息
        Question question = getById(dto.getQuestionId());
        return remoteCallAiCodeSuggest(question, userSubmit);
    }

    /**
     * 调用 ai 服务的问答接口进行题目解析
     */
    private QuestionAnalysisVO remoteCallAiAnalysis(Question question, Integer programType) {

        Map<String, String> contentTemplate = buildMessageContentTemplate(question, programType);
        contentTemplate.put("需求", "请给我输出这个题目的解析, 简单易懂就行, 不要给我代码, 我只要解题思路, 方便我解出这个题. 不要说好的, 直接给我解析, 不需要过多的废话!");
        ChatDTO chatDTO = buildChatDTO(contentTemplate);

        // 调用 ai 成功
        ChatVO chatVO = remoteCallAiChatAsk(chatDTO);

        QuestionAnalysisVO questionAnalysisVO = new QuestionAnalysisVO();
        questionAnalysisVO.setQuestionId(question.getQuestionId());
        questionAnalysisVO.setModel(chatVO.getModel());
        questionAnalysisVO.setAnalysis(chatVO.getCurrentContent());

        // 缓存
        questionCacheManager.setAnalysis(questionAnalysisVO);

        log.info("调用 AI 服务 ask 接口进行题目解析成功, 题目 id: {}", question.getQuestionId());

        return questionAnalysisVO;
    }

    /**
     *
     * 调用 ai 服务的问答接口进行代码建议
     */
    private QuestionCodeSuggestVO remoteCallAiCodeSuggest(Question question, UserSubmit userSubmit) {
        Map<String, String> contentTemplate = buildMessageContentTemplate(question, userSubmit.getProgramType());
        String prompt = """
                参考我给你的题目内容, 然后查看我的代码, 查看默认代码, 给出我代码的优化建议, 接着给出优化后的代码.
                也就是说, 排除默认代码后的部分, 是我写的代码, 只用针对我写的代码分析优化就行, 不要说好的, 直接给我就行, 不要关注主函数, 不需要过多的废话!
                只用对[我的代码] 给出优化就行!
                如果没有优化空间, 就返回：你的代码已经很优秀了, 不需要优化啦！
                如果还有优化空间, 就直接以： **优化建议** 开头
                整体回答干净利落, 不要有过多的口语，
                """;
        contentTemplate.put("需求", prompt);
        contentTemplate.put("我的代码", userSubmit.getUserSubmitCode());
        ChatDTO chatDTO = buildChatDTO(contentTemplate);
        ChatVO chatVO = remoteCallAiChatAsk(chatDTO);

        QuestionCodeSuggestVO questionCodeSuggestVO = new QuestionCodeSuggestVO();
        questionCodeSuggestVO.setQuestionId(question.getQuestionId());
        questionCodeSuggestVO.setModel(chatVO.getModel());
        questionCodeSuggestVO.setSuggest(chatVO.getCurrentContent());

        // 缓存此次题目对应的代码优化信息: 用户id:题目id:提交记录uuid
        questionCacheManager.setCodeSuggest(userSubmit.getUserId(), userSubmit.getQuestionId(), userSubmit.getUuid(), questionCodeSuggestVO);

        log.info("调用 AI 服务 ask 接口进行用户代码优化建议成功, 题目 id: {}", question.getQuestionId());

        return questionCodeSuggestVO;
    }

    /**
     * 远程调用 AI 服务的回答接口
     * @param chatDTO 入参
     * @return ChatVO
     */
    private ChatVO remoteCallAiChatAsk(ChatDTO chatDTO) {
        R<ChatVO> res = remoteChatService.ask(chatDTO);
        if (res.getCode() != ResultCode.SUCCESS.getCode()) {
            log.info("调用ai服务失败, 状态码: {} 失败原因: {}, ", res.getCode(), res.getMsg());
            throw new ServiceException(ResultCode.AI_CHAT_FAILED);
        }
        return res.getData();
    }

    /**
     * 构造调用 ai 服务的入参实体
     */
    private ChatDTO buildChatDTO(Map<String, String> content) {
        ChatDTO chatDTO = new ChatDTO();
        List<Message> messages = new ArrayList<>();
        Message message = Message.builder().role("user").content(content.toString()).build();
        messages.add(message);
        chatDTO.setMessages(messages);
        chatDTO.setKey(aiKey);
        return chatDTO;
    }

    /**
     * 获取要提问的内容模板
     */
    private Map<String, String> buildMessageContentTemplate(Question question, Integer programType) {
        Map<String, String> map = new HashMap<>();
        map.put("题目标题", question.getTitle());
        map.put("题目内容", question.getContent());
        map.put("默认代码", question.getDefaultCode());
        map.put("主函数", question.getMainFuc());
        map.put("使用编程语言", ProgramType.getByValue(programType).getDesc());
        return map;
    }

    /**
     * 通过题目 id 获取实体对象
     */
    private Question getById(Long questionId) {
        Question question = new Question();
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        if (questionES != null) {
            BeanUtil.copyProperties(questionES, question);
            return question;
        }
        Question dbQuestion = questionMapper.selectById(questionId);
        if (dbQuestion == null) {
            throw new ServiceException(ResultCode.QUESTION_NOT_EXISTS);
        }
        refreshQuestion();
        BeanUtil.copyProperties(question, dbQuestion);
        return question;
    }
}
